const Menu = require('../../domain/menu/menu')
const Usecase = require('../../shared/usecase/Usecase')
const { SystemNotFoundError } = require('../../domain/system/error')

class GetAuthMenu extends Usecase {
  constructor({ userRepo, menuRepo, systemRepo }) {
    super()
    this.userRepo = userRepo
    this.menuRepo = menuRepo
    this.systemRepo = systemRepo
  }

  async execute({ systemCode }, currentUser) {
    const system = await this.systemRepo.findOne({
      where: { code: systemCode },
      include: ['menuList'],
    })
    if (!system) throw new SystemNotFoundError(systemCode)
    if (currentUser.isSuperAdmin) {
      return system.getMenuListAndButtonList()
    }
    return Menu.listGroupByType(
      await this.userRepo.findUserSystemMenu(currentUser.id, system.id)
    )
  }
}

module.exports = GetAuthMenu
